package com.heiye.auth.sms;

import cn.hutool.json.JSONUtil;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teautil.models.RuntimeOptions;
import com.heiye.auth.enums.ResponseCodeEnum;
import com.heiye.framework.common.exception.BizException;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @Author: heiye
 * @CreateTime: 2024/09/14 下午12:51
 * @Description: 发送短信业务
 * @Version: 1.0
 */
@Slf4j
@Component
public class AliyunSmsHelper {

    @Resource
    private Client client;

    /**
     * 发送验证码
     *
     * @param phoneNumber 需要发送验证码的手机
     * @param code        已经生成好的验证码
     */
    public void sendVerifyCode(String phoneNumber, String code) {
        // 构建发送请求
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(phoneNumber)
                .setSignName("黑夜")
                .setTemplateCode("SMS_473425046")
                .setTemplateParam("{\"code\":\"" + code + "\"}");

        try {
            log.info("==> 开始短信发送, phone: {}, code: {}", phoneNumber, code);

            // 发送请求
            SendSmsResponse response = client.sendSmsWithOptions(sendSmsRequest, new RuntimeOptions());

            log.info("==> 短信发送成功, response: {}", JSONUtil.toJsonStr(response));

        } catch (Exception e) {
            log.error("==> 短信发送错误: ", e);
            throw new BizException(ResponseCodeEnum.SYSTEM_ERROR);
        }
    }
}
